#include "textureUtil.hpp"
#include <QImage>
#include <QDebug>

 GLuint TextureUtil::loadTexture( const QString& imgPath, QOpenGLFunctions_3_3_Core* gl ) {
    QImage img;
    if ( !img.load( imgPath ) ) {
        qDebug() << "纹理加载失败:" << imgPath;
        return 0;
    }

    // QImage 需要垂直翻转
    img = img.mirrored( /*horizontally*/false, /*vertically*/true );

    GLuint textureID;
    gl->glGenTextures( 1, &textureID );
    gl->glBindTexture( GL_TEXTURE_2D, textureID );
    gl->glTexImage2D (
        /* target */        GL_TEXTURE_2D,
        /*level*/           0,
        /*internalformat*/  GL_RGBA,
        /*w*/               img.width(),
        /*h*/               img.height(),
        /*border*/          0,
        /*format*/          GL_RGBA,
        /*type*/            GL_UNSIGNED_BYTE,
        /*pixels*/          img.bits()
    );

    gl->glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
    gl->glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
    gl->glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
    gl->glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
    qDebug() << "纹理加载成功" << textureID;

    return textureID;
 }